import 'dart:convert';
import 'dart:typed_data';

import 'package:base_moudle/index.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

import '../../../models/data_model/HyWorkModel.dart';

///个人项目ID
const String ME_CODE_companyKey = '0000';

class HyWorkAppModel extends BaseDBProvider {
  HyWorkAppModel({
    int? id,
    String? userId,
    String? appName,
    String? appType,
    String? companyId,
    int isEnabled = 1,
    int isShow = 0,
    int isAll = 1,
    int rank = 0,
    String? creatorTime,
    String? updateTime,
    String? iconName,
    String? routeName,
    String? userKye,
  }) {
    _id = id;
    _userId = userId;
    _appName = appName;
    _iconName = iconName;
    _routeName = routeName;
    _companyId = companyId;
    _appType = appType;
    _isEnabled = isEnabled;
    _isShow = isShow;
    _isAll = isAll;
    _rank = rank;
    _creatorTime =
        creatorTime ?? DateTime.now().millisecondsSinceEpoch.toString();
    _updateTime = updateTime;
    _userKye = userKye;
  }

  int? _id;

  String? _userId;

  String? _appName;

  String? _appType;

  int _isEnabled = 1;

  int _isAll = 1;
  int _rank = 0;

  int? _isShow;
  String? _creatorTime = DateTime.now().millisecondsSinceEpoch.toString();
  String? _updateTime;

  String? _iconName;
  String? _routeName;
  String? _companyId;
  String? _userKye;

  ///唯一
  ///'isAll|userId|companyId|appName'
  String? get userKye => _userKye;

  ///主键
  int? get id => _id;

  ///用户ID 主键
  String? get userId => _userId;

  /// 名称
  String? get appName => _appName;

  /// app类型
  String? get appType => _appType;

  /// 公司ID
  String? get companyId => _companyId;

  /// 是否启用
  int get isEnabled => _isEnabled;

  ///1 工作台，0是企业项目
  int get isAll => _isAll;

  /// 显示隐藏
  int? get isShow => _isShow;

  String? get creatorTime => _creatorTime;

  ///记录最近使用操作 isAll =0 起作用
  String? get updateTime => _updateTime;

  String? get iconName => _iconName;

  String? get routeName => _routeName;

  int get rank => _rank;

  bool get isDisplay => (isShow ?? 0) == 1;

  HyWorkAppModel.fromJson(json) {
    _id = json['id'];
    _userId = json['userId'];
    _appName = json['appName'];
    _companyId = json['companyId'];
    _appType = json['appType'];
    _isEnabled = json['isEnabled'];
    _isAll = json['isAll'];
    _isShow = json['isShow'];
    _userKye = json['userKye'];
    _rank = json['rank'];
    _iconName = json['iconName'];
    _routeName = json['routeName'];
    _updateTime = json['updateTime'];
    _creatorTime = json['creatorTime'];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'appName': appName,
      'companyId': companyId,
      'appType': appType,
      'isEnabled': isEnabled,
      'isAll': isAll,
      'rank': rank,
      'userKye': userKye,
      'isShow': isShow,
      'iconName': iconName,
      'routeName': routeName,
      'creatorTime': creatorTime,
      'updateTime': updateTime,
    };
  }

  ItemModel toModel() {
    return ItemModel(
        title: appName ?? '',
        iconName: iconName ?? '',
        routeName: routeName ?? '',
        type: appType ?? '',
        isDisplay: isShow == 1);
  }

  static List<HyWorkAppModel> listFromJson(json) {
    final List<HyWorkAppModel> res = [];
    json.forEach((element) {
      res.add(HyWorkAppModel.fromJson(element));
    });
    return res;
  }

  @override
  String tableSqlString() {
    return '${tableBaseString()}  userId text,appName text,appType text,iconName text,routeName text,isEnabled integer,isAll integer,isShow integer,creatorTime text,updateTime text,companyId text,rank integer,userKye text UNIQUE';
  }

  Future<int> insertOrUpdateFormCache() async {
    if (id == null) {
      return insertDB();
    } else {
      return updateDB();
    }
  }

  Future<int> insertDB() async {
    return await insert(toJson());
  }

  Future<int> updateDB() async {
    return await update(toJson(), 'id=$id');
  }

  Future<int> deleteDb() async {
    return await delete('id=$_id');
  }

  ///获取当前所有app code 1:工作台，0:企业项目,2:个人版
  static Future<List<HyWorkAppModel>> allList(
      {bool isRank = false,
      int code = 1,
      bool? isEnabled,
      bool? isShow,
      String? appType,
      List<String>? appTypes,
      List<String>? appNames,
      String? appName,
      String? orderBySql,
      bool? updateTime}) async {
    String? companyId = ZsMemeryCache.zsWorkLoginModel?.workModuleUserId;
    if (code == 2) {
      companyId = ME_CODE_companyKey;
    }

    String whereSql =
        ' userId =="${ZsMemeryCache.loginDataModel?.userId}"  AND companyId =="$companyId"';

    whereSql += ' AND isAll = $code';

    if (isShow != null) {
      whereSql += ' AND isShow = ${isShow ? 1 : 0}';
    }
    if (isEnabled != null) {
      whereSql += ' AND isEnabled = ${isEnabled ? 1 : 0}';
    }
    if (appType != null) {
      whereSql += ' AND appType = "$appType"';
    }
    if (appNames != null) {
      whereSql += ' AND appName IN ("${appNames.join('","')}")';
    }

    if (appName != null) {
      whereSql += ' AND appName = "$appName"';
    }
    if (updateTime != null) {
      whereSql += ' AND updateTime != "null" ';
    }

    String? orderBy;
    if (isRank) {
      orderBy = 'rank asc';
    }

    final res = await HyWorkAppModel()
        .select(where: whereSql, orderBy: orderBySql ?? orderBy);
    return HyWorkAppModel.listFromJson(res);
  }

  /// 获取企业显示的 和不显示的
  static Future<List<HyWorkAppModel>> workList({bool? isShow}) async {
    return allList(code: 0, isShow: isShow);
  }

  ///最近使用的
  static Future<List<HyWorkAppModel>> timeList(
      {bool? isShow, int code = 1}) async {
    return allList(
        code: code,
        isShow: isShow,
        updateTime: true,
        isEnabled: true,
        orderBySql: 'updateTime desc');
  }

  ///初始新增
  static Future<void> saveModel(
      {required ItemModel model,
      int code = 1,
      bool isEnabled = true,
      bool isIndividual = false,
      int rank = 0}) async {
    if (ZsMemeryCache.loginDataModel?.userId == null) {
      return;
    }
    String? companyId = ZsMemeryCache.zsWorkLoginModel?.workModuleUserId;
    if (code == 2) {
      companyId = ME_CODE_companyKey;
    }
    String str =
        '$code|${ZsMemeryCache.loginDataModel?.userId}|$companyId|${model.title}';
    String id = generateMd5(str);
    final HyWorkAppModel md = HyWorkAppModel(
      userId: ZsMemeryCache.loginDataModel?.userId,
      isAll: code,
      appName: model.title,
      appType: model.type,
      iconName: model.iconName,
      routeName: model.routeName,
      companyId: companyId,
      isShow: model.isDisplay ? 1 : 0,
      isEnabled: isEnabled ? 1 : 0,
      rank: rank,
      userKye: id,
    );
    try {
      final int ok = await md.insertDB();
      print('$model  -- $ok');
    } catch (e) {
      print('$model  -- 新增失败:$e');
    }
  }

  static Future<void> saveClickModel(
      {required ItemModel model, int code = 1}) async {
    final List<HyWorkAppModel> arr = await HyWorkAppModel.allList(
        appName: model.title, appType: model.type, code: code);
    for (HyWorkAppModel element in arr) {
      element.saveKeyModel(dict: {
        'updateTime': DateTime.now().millisecondsSinceEpoch.toString()
      });
    }
  }

  ///添加常用
  static Future<void> saveAddLikeModel(
      {required ItemModel model, int code = 1, int rank = 0}) async {
    final List<HyWorkAppModel> arr = await HyWorkAppModel.allList(
        code: code, appName: model.title, appType: model.type);
    for (HyWorkAppModel element in arr) {
      element.saveKeyModel(dict: {'isShow': 1, 'rank': rank});
    }
  }

  ///删除常用
  static Future<void> saveCancelLikeModel(
      {required ItemModel model, int code = 1}) async {
    final List<HyWorkAppModel> arr = await HyWorkAppModel.allList(
        code: code, appName: model.title, appType: model.type);
    for (HyWorkAppModel element in arr) {
      element.saveKeyModel(dict: {'isShow': 0});
    }
  }

  Future<void> saveKeyModel({required Map<String, dynamic> dict}) async {
    final Map<String, dynamic> json = toJson();
    json.addAll(dict);
    final HyWorkAppModel md = HyWorkAppModel.fromJson(json);
    await md.updateDB();
  }

  static Future<void> delect({
    int code = 1,
    String? appName,
    String? appType,
    List<String>? appTypes,
    List<String>? appNames,
  }) async {
    var arr = await allList(
        code: code,
        appName: appName,
        appType: appType,
        appTypes: appTypes,
        appNames: appNames);
    for (HyWorkAppModel item in arr) {
      item.deleteDb();
    }
  }
}

String generateMd5(String data) {
  Uint8List content = new Utf8Encoder().convert(data);
  Digest digest = md5.convert(content);
  // 这里其实就是 digest.toString()
  return hex.encode(digest.bytes);
}
